package com.xlhj.boot.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.*;
import com.xlhj.boot.service.OssService;
import com.xlhj.boot.util.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.List;

/**
 * @author: caijliu
 * @description: OssServiceImpl
 * @data: 23/06/2021 16:01
 */
@Service
public class OssServiceImpl implements OssService {

    @Value("${aliyun.config.accessId}")
    private String accessId;
    @Value("${aliyun.config.accessKey}")
    private String accessKey;
    @Value("${aliyun.config.ossEndPoint}")
    private String endPoint;
    private AppendObjectResult objectResult;

    @Override
    public ResponseMessage appendDataToOss(String content, int type) {
        System.out.println("追加得信息为：" + content);
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessId, accessKey);
        ObjectMetadata metadata = new ObjectMetadata();
        //设置上传文件类型
        metadata.setContentType("text/plain");
        //设置请求参数
        AppendObjectRequest objectRequest = new AppendObjectRequest("data-api-bucket", DateUtils.getLocalDateStr() + "/user_info.csv", new ByteArrayInputStream(content.getBytes()), metadata);
        //先追加列信息
        if (0 == type) {
            objectRequest.setPosition(0L);
        } else {
            //再次追加数据
            objectRequest.setPosition(objectResult.getNextPosition());
            objectRequest.setInputStream(new ByteArrayInputStream(content.getBytes()));
        }
        objectResult = ossClient.appendObject(objectRequest);
        ResponseMessage response = objectResult.getResponse();
        return response;
    }

    @Override
    public void getFileInfoForMarker() {
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessId, accessKey);
        final String keyPrefix = DateUtils.getLocalDateStr() + "/user_info";
        ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest("data-api-bucket").withPrefix(keyPrefix));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        for (OSSObjectSummary sum : sums) {
            long size = sum.getSize();
        }
    }

























}
